import React, { Suspense, lazy, ComponentType } from 'react';
import { Spin } from 'antd';

/**
 * 懒加载组件包装器
 */
export function lazyLoad<T extends ComponentType<any>>(
  importFunc: () => Promise<{ default: T }>,
  fallback?: React.ReactNode
) {
  const LazyComponent = lazy(importFunc);

  return (props: React.ComponentProps<T>) => (
    <Suspense fallback={fallback || <DefaultFallback />}>
      <LazyComponent {...props} />
    </Suspense>
  );
}

/**
 * 默认加载组件
 */
function DefaultFallback() {
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '200px',
      width: '100%'
    }}>
      <Spin size="large" tip="加载中..." />
    </div>
  );
}

/**
 * 页面级懒加载
 */
export function lazyLoadPage<T extends ComponentType<any>>(
  importFunc: () => Promise<{ default: T }>
) {
  return lazyLoad(importFunc, <PageLoadingFallback />);
}

/**
 * 页面加载组件
 */
function PageLoadingFallback() {
  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'center',
      minHeight: '100vh',
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
    }}>
      <Spin size="large" style={{ marginBottom: 24 }} />
      <h2 style={{ color: '#fff' }}>正在加载页面...</h2>
    </div>
  );
}

/**
 * 带重试的懒加载
 */
export function lazyLoadWithRetry<T extends ComponentType<any>>(
  importFunc: () => Promise<{ default: T }>,
  retries = 3,
  delay = 1000
) {
  const retryImport = async (): Promise<{ default: T }> => {
    try {
      return await importFunc();
    } catch (error) {
      if (retries > 0) {
        await new Promise(resolve => setTimeout(resolve, delay));
        return retryImport();
      }
      throw error;
    }
  };

  return lazyLoad(retryImport);
}